// 测评记录管理 JavaScript
let currentPage = 1;
let currentFilters = {};
let currentAssessmentId = null;

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    // 检查管理员token
    const adminToken = localStorage.getItem('adminToken');
    if (!adminToken) {
        showAlert('请先登录管理员账户', 'error');
        setTimeout(() => {
            window.location.href = '/admin-portal';
        }, 2000);
        return;
    }
    
    loadStatistics();
    loadAssessments();
    loadScaleOptions();
});

// 加载统计信息
function loadStatistics() {
    fetch('/api/admin/assessments/statistics', {
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('adminToken')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const stats = data.data;
            document.getElementById('totalAssessments').textContent = stats.total_assessments;
            document.getElementById('completedAssessments').textContent = stats.completed_assessments;
            document.getElementById('inProgressAssessments').textContent = stats.in_progress_assessments;
            document.getElementById('anonymousAssessments').textContent = stats.anonymous_assessments;
            
            // 计算百分比
            const completionRate = stats.total_assessments > 0 ? 
                Math.round((stats.completed_assessments / stats.total_assessments) * 100) : 0;
            const anonymousRate = stats.total_assessments > 0 ? 
                Math.round((stats.anonymous_assessments / stats.total_assessments) * 100) : 0;
            
            document.getElementById('completionRate').textContent = completionRate + '%';
            document.getElementById('anonymousRate').textContent = anonymousRate + '%';
            document.getElementById('assessmentGrowth').textContent = '+' + (stats.growth || 0) + '%';
            document.getElementById('activeUsers').textContent = '活跃 ' + (stats.active_users || 0);
        }
    })
    .catch(error => {
        console.error('Error loading statistics:', error);
        // 使用现有的API接口获取基本统计
        loadBasicStatistics();
    });
}

// 加载基本统计信息（使用现有API）
function loadBasicStatistics() {
    fetch('/api/admin/assessments?per_page=1', {
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('adminToken')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const total = data.data.pagination.total;
            document.getElementById('totalAssessments').textContent = total;
            
            // 简化统计显示
            document.getElementById('completedAssessments').textContent = '-';
            document.getElementById('inProgressAssessments').textContent = '-';
            document.getElementById('anonymousAssessments').textContent = '-';
            document.getElementById('completionRate').textContent = '-%';
            document.getElementById('anonymousRate').textContent = '-%';
            document.getElementById('assessmentGrowth').textContent = '+0%';
            document.getElementById('activeUsers').textContent = '活跃 0';
        }
    })
    .catch(error => console.error('Error loading basic statistics:', error));
}

// 加载测评记录列表
function loadAssessments(page = 1) {
    currentPage = page;
    
    // 构建查询参数
    const params = new URLSearchParams({
        page: page,
        per_page: 20,
        ...currentFilters
    });
    
    fetch(`/api/admin/assessments?${params}`, {
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('adminToken')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            displayAssessments(data.data.assessments);
            displayPagination(data.data.pagination);
            updateAssessmentCount(data.data.pagination.total);
        } else {
            showAlert('加载测评记录失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('加载测评记录失败', 'error');
    });
}

// 显示测评记录列表
function displayAssessments(assessments) {
    const tbody = document.getElementById('assessmentsTableBody');
    
    if (assessments.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="9" class="text-center py-5">
                    <i class="bi bi-inbox fs-1 text-muted"></i>
                    <p class="mt-2 text-muted">暂无测评记录</p>
                </td>
            </tr>
        `;
        return;
    }
    
    tbody.innerHTML = assessments.map(assessment => `
        <tr>
            <td>
                <input type="checkbox" class="form-check-input assessment-checkbox" value="${assessment.id}">
            </td>
            <td>
                <div>
                    ${assessment.user_id ? `
                        <h6 class="mb-1">${assessment.username || '未知用户'}</h6>
                        <small class="text-muted">ID: ${assessment.user_id}</small>
                    ` : `
                        <h6 class="mb-1 text-muted">匿名用户</h6>
                        <small class="text-muted">IP: ${assessment.ip_address || '未知'}</small>
                    `}
                </div>
            </td>
            <td>
                <div>
                    <h6 class="mb-1">${assessment.scale_title || '未知量表'}</h6>
                    <small class="text-muted">ID: ${assessment.scale_id}</small>
                </div>
            </td>
            <td>
                <span class="badge ${getStatusBadgeClass(assessment.status)}">
                    ${getStatusText(assessment.status)}
                </span>
            </td>
            <td>
                <div class="progress" style="height: 8px;">
                    <div class="progress-bar ${getProgressBarClass(assessment.status)}" 
                         role="progressbar" 
                         style="width: ${assessment.progress_percentage || 0}%">
                    </div>
                </div>
                <small class="text-muted">${Math.round(assessment.progress_percentage || 0)}%</small>
            </td>
            <td>
                <span class="badge bg-light text-dark">
                    ${formatDuration(assessment.time_spent)}
                </span>
            </td>
            <td>
                <small>${formatDateTime(assessment.started_at)}</small>
            </td>
            <td>
                <small>${assessment.completed_at ? formatDateTime(assessment.completed_at) : '-'}</small>
            </td>
            <td>
                <div class="btn-group btn-group-sm">
                    <button class="btn btn-outline-primary" onclick="viewAssessmentDetail(${assessment.id})" title="查看详情">
                        <i class="bi bi-eye"></i>
                    </button>
                    <button class="btn btn-outline-info" onclick="exportAssessmentReport(${assessment.id})" title="导出报告">
                        <i class="bi bi-download"></i>
                    </button>
                    <div class="btn-group btn-group-sm">
                        <button class="btn btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown">
                            <i class="bi bi-three-dots"></i>
                        </button>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="#" onclick="viewUserProfile(${assessment.user_id})">
                                <i class="bi bi-person me-2"></i>查看用户
                            </a></li>
                            <li><a class="dropdown-item" href="#" onclick="viewScaleDetail(${assessment.scale_id})">
                                <i class="bi bi-clipboard-data me-2"></i>查看量表
                            </a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item text-danger" href="#" onclick="deleteAssessment(${assessment.id})">
                                <i class="bi bi-trash me-2"></i>删除记录
                            </a></li>
                        </ul>
                    </div>
                </div>
            </td>
        </tr>
    `).join('');
}

// 显示分页
function displayPagination(pagination) {
    const paginationElement = document.getElementById('pagination');
    
    if (pagination.pages <= 1) {
        paginationElement.innerHTML = '';
        return;
    }
    
    let paginationHTML = '';
    
    // 上一页
    if (pagination.has_prev) {
        paginationHTML += `
            <li class="page-item">
                <a class="page-link" href="#" onclick="loadAssessments(${pagination.page - 1})">上一页</a>
            </li>
        `;
    }
    
    // 页码
    for (let i = Math.max(1, pagination.page - 2); i <= Math.min(pagination.pages, pagination.page + 2); i++) {
        paginationHTML += `
            <li class="page-item ${i === pagination.page ? 'active' : ''}">
                <a class="page-link" href="#" onclick="loadAssessments(${i})">${i}</a>
            </li>
        `;
    }
    
    // 下一页
    if (pagination.has_next) {
        paginationHTML += `
            <li class="page-item">
                <a class="page-link" href="#" onclick="loadAssessments(${pagination.page + 1})">下一页</a>
            </li>
        `;
    }
    
    paginationElement.innerHTML = paginationHTML;
}

// 更新测评记录数量显示
function updateAssessmentCount(total) {
    document.getElementById('assessmentCount').textContent = `共 ${total} 条记录`;
}

// 搜索测评记录
function searchAssessments() {
    currentFilters = {
        search: document.getElementById('searchInput').value.trim(),
        status: document.getElementById('statusFilter').value,
        user_type: document.getElementById('userTypeFilter').value,
        scale_id: document.getElementById('scaleFilter').value,
        time_range: document.getElementById('timeFilter').value
    };
    
    // 移除空值
    Object.keys(currentFilters).forEach(key => {
        if (!currentFilters[key]) {
            delete currentFilters[key];
        }
    });
    
    loadAssessments(1);
}

// 查看测评详情
function viewAssessmentDetail(assessmentId) {
    currentAssessmentId = assessmentId;
    
    fetch(`/api/admin/assessments/${assessmentId}`, {
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('adminToken')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            displayAssessmentDetail(data.data);
            new bootstrap.Modal(document.getElementById('assessmentDetailModal')).show();
        } else {
            showAlert('获取测评详情失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('获取测评详情失败', 'error');
    });
}

// 显示测评详情
function displayAssessmentDetail(assessment) {
    const content = document.getElementById('assessmentDetailContent');
    
    content.innerHTML = `
        <div class="row">
            <div class="col-md-6">
                <h6>基本信息</h6>
                <table class="table table-sm">
                    <tr><td>测评ID:</td><td>${assessment.id}</td></tr>
                    <tr><td>用户:</td><td>${assessment.user_id ? assessment.username : '匿名用户'}</td></tr>
                    <tr><td>量表:</td><td>${assessment.scale_title}</td></tr>
                    <tr><td>状态:</td><td><span class="badge ${getStatusBadgeClass(assessment.status)}">${getStatusText(assessment.status)}</span></td></tr>
                    <tr><td>进度:</td><td>${Math.round(assessment.progress_percentage || 0)}%</td></tr>
                </table>
            </div>
            <div class="col-md-6">
                <h6>时间信息</h6>
                <table class="table table-sm">
                    <tr><td>开始时间:</td><td>${formatDateTime(assessment.started_at)}</td></tr>
                    <tr><td>完成时间:</td><td>${assessment.completed_at ? formatDateTime(assessment.completed_at) : '-'}</td></tr>
                    <tr><td>用时:</td><td>${formatDuration(assessment.time_spent)}</td></tr>
                    <tr><td>IP地址:</td><td>${assessment.ip_address || '-'}</td></tr>
                </table>
            </div>
        </div>
        
        ${assessment.scores && assessment.scores.length > 0 ? `
            <div class="mt-4">
                <h6>测评结果</h6>
                <div class="row">
                    ${assessment.scores.map(score => `
                        <div class="col-md-4 mb-3">
                            <div class="card">
                                <div class="card-body p-3">
                                    <h6 class="card-title">${score.dimension_name}</h6>
                                    <p class="card-text">
                                        <strong>得分:</strong> ${score.raw_score}<br>
                                        <strong>等级:</strong> ${score.score_level || '-'}
                                    </p>
                                </div>
                            </div>
                        </div>
                    `).join('')}
                </div>
            </div>
        ` : ''}
    `;
}

// 导出测评报告
function exportAssessmentReport(assessmentId) {
    const url = `/api/admin/assessments/${assessmentId}/export`;
    const link = document.createElement('a');
    link.href = url;
    link.download = `assessment_${assessmentId}_report.pdf`;
    link.click();
}

// 导出单个测评报告
function exportSingleAssessment() {
    if (currentAssessmentId) {
        exportAssessmentReport(currentAssessmentId);
    }
}

// 查看用户资料
function viewUserProfile(userId) {
    if (userId) {
        window.open(`/admin/users/${userId}`, '_blank');
    }
}

// 查看量表详情
function viewScaleDetail(scaleId) {
    if (scaleId) {
        window.open(`/admin/scales/${scaleId}`, '_blank');
    }
}

// 删除测评记录
function deleteAssessment(assessmentId) {
    if (confirm('确定要删除这条测评记录吗？此操作不可撤销！')) {
        fetch(`/api/admin/assessments/${assessmentId}`, {
            method: 'DELETE',
            headers: {
                'Authorization': 'Bearer ' + localStorage.getItem('adminToken')
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('删除成功', 'success');
                loadAssessments(currentPage);
                loadStatistics();
            } else {
                showAlert('删除失败: ' + data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showAlert('删除失败', 'error');
        });
    }
}

// 导出测评数据
function exportAssessments() {
    const params = new URLSearchParams(currentFilters);
    const url = `/api/admin/assessments/export?${params}`;
    
    // 创建下载链接
    const link = document.createElement('a');
    link.href = url;
    link.download = `assessments_${new Date().toISOString().split('T')[0]}.xlsx`;
    link.click();
    
    showAlert('导出任务已开始，请稍候下载', 'info');
}

// 批量导出
function batchExport() {
    const selectedIds = getSelectedAssessmentIds();
    if (selectedIds.length === 0) {
        showAlert('请选择要导出的测评记录', 'warning');
        return;
    }
    
    const params = new URLSearchParams({
        ids: selectedIds.join(',')
    });
    
    const url = `/api/admin/assessments/batch-export?${params}`;
    const link = document.createElement('a');
    link.href = url;
    link.download = `batch_assessments_${new Date().toISOString().split('T')[0]}.xlsx`;
    link.click();
    
    bootstrap.Modal.getInstance(document.getElementById('batchOperationModal')).hide();
    showAlert('批量导出任务已开始', 'success');
}

// 批量归档
function batchArchive() {
    const selectedIds = getSelectedAssessmentIds();
    if (selectedIds.length === 0) {
        showAlert('请选择要归档的测评记录', 'warning');
        return;
    }
    
    if (confirm(`确定要归档选中的 ${selectedIds.length} 条测评记录吗？`)) {
        fetch('/api/admin/assessments/batch-archive', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem('adminToken')
            },
            body: JSON.stringify({
                assessment_ids: selectedIds
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('批量归档成功', 'success');
                loadAssessments(currentPage);
                loadStatistics();
            } else {
                showAlert('批量归档失败: ' + data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showAlert('批量归档失败', 'error');
        });
        
        bootstrap.Modal.getInstance(document.getElementById('batchOperationModal')).hide();
    }
}

// 批量删除
function batchDelete() {
    const selectedIds = getSelectedAssessmentIds();
    if (selectedIds.length === 0) {
        showAlert('请选择要删除的测评记录', 'warning');
        return;
    }
    
    if (confirm(`确定要删除选中的 ${selectedIds.length} 条测评记录吗？此操作不可撤销！`)) {
        fetch('/api/admin/assessments/batch-delete', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem('adminToken')
            },
            body: JSON.stringify({
                assessment_ids: selectedIds
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('批量删除成功', 'success');
                loadAssessments(currentPage);
                loadStatistics();
            } else {
                showAlert('批量删除失败: ' + data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showAlert('批量删除失败', 'error');
        });
        
        bootstrap.Modal.getInstance(document.getElementById('batchOperationModal')).hide();
    }
}

// 获取选中的测评记录ID
function getSelectedAssessmentIds() {
    const checkboxes = document.querySelectorAll('.assessment-checkbox:checked');
    return Array.from(checkboxes).map(cb => parseInt(cb.value));
}

// 刷新统计
function refreshStatistics() {
    loadStatistics();
    showAlert('统计信息已刷新', 'success');
}

// 加载量表选项
function loadScaleOptions() {
    fetch('/api/admin/scales?per_page=100', {
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('adminToken')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const scaleFilter = document.getElementById('scaleFilter');
            data.data.scales.forEach(scale => {
                const option = document.createElement('option');
                option.value = scale.id;
                option.textContent = scale.title;
                scaleFilter.appendChild(option);
            });
        }
    })
    .catch(error => console.error('Error loading scale options:', error));
}

// 工具函数
function getStatusBadgeClass(status) {
    const classes = {
        'completed': 'bg-success',
        'in_progress': 'bg-warning',
        'abandoned': 'bg-secondary',
        'expired': 'bg-danger'
    };
    return classes[status] || 'bg-secondary';
}

function getStatusText(status) {
    const texts = {
        'completed': '已完成',
        'in_progress': '进行中',
        'abandoned': '已放弃',
        'expired': '已过期'
    };
    return texts[status] || status;
}

function getProgressBarClass(status) {
    const classes = {
        'completed': 'bg-success',
        'in_progress': 'bg-warning',
        'abandoned': 'bg-secondary',
        'expired': 'bg-danger'
    };
    return classes[status] || 'bg-primary';
}

function formatDuration(seconds) {
    if (!seconds) return '0秒';
    
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = seconds % 60;
    
    if (hours > 0) {
        return `${hours}时${minutes}分${secs}秒`;
    } else if (minutes > 0) {
        return `${minutes}分${secs}秒`;
    } else {
        return `${secs}秒`;
    }
}

function formatDateTime(dateString) {
    if (!dateString) return '-';
    return new Date(dateString).toLocaleString('zh-CN');
}

function showAlert(message, type = 'info') {
    const alertClass = type === 'error' ? 'alert-danger' : 
                      type === 'success' ? 'alert-success' : 
                      type === 'warning' ? 'alert-warning' : 'alert-info';
    
    const alertHTML = `
        <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    
    // 在页面顶部显示提示
    const container = document.querySelector('.content-scroll');
    if (container) {
        container.insertAdjacentHTML('afterbegin', alertHTML);
        
        // 3秒后自动消失
        setTimeout(() => {
            const alert = container.querySelector('.alert');
            if (alert) {
                bootstrap.Alert.getOrCreateInstance(alert).close();
            }
        }, 3000);
    }
}

// 全选功能
document.addEventListener('DOMContentLoaded', function() {
    const selectAllCheckbox = document.getElementById('selectAll');
    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', function() {
            const checkboxes = document.querySelectorAll('.assessment-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = this.checked;
            });
        });
    }
});

// 搜索框回车事件
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('searchInput');
    if (searchInput) {
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                searchAssessments();
            }
        });
    }
}); 